package com.mpsc.multi.source.config.interceptor;

import com.mpsc.multi.source.config.datasource.DataSourceContextHolder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ServiceLoader;

@Component
public class DynamicDataSourceInterceptor implements HandlerInterceptor {

    private static long num = 2;

    private static long MULTI_SOURCE = 2;

    //polling-type: polling
    @Value("${spring.rule.polling-type:polling}")
    private String pollingType;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        ServiceLoader<DataSourceRoute> dataSourceRoute = ServiceLoader.load(DataSourceRoute.class);
        for (DataSourceRoute route: dataSourceRoute){
            if(route.getRouteType().equals(pollingType.trim())){
                num = route.dataSourceRoute();
            }
        }


        String  shardingId = request.getParameter("shardingId");
        try {
            if (num++ % MULTI_SOURCE == 0) {
                dataSource = "db1";
            } else {
                dataSource = "db2";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) {
        DataSourceContextHolder.clearDB();
    }
}
